<?php


namespace App\Http\Controllers\Admin\Mall;


use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;

//商品子分类
class ProductSubCateController extends BaseController
{
    /**
     * @api {post} /mall/product-sub-cate 添加商品子分类
     *
     * @apiGroup 个性商城-商品子分类
     *
     * @apiParam {String} sub_cate_name 子分类名称，必须
     * @apiParam {String} p_cate_ids 父分类，多个之间用英文逗号隔开，必须
     * @apiParam {Int} status 状态：1：显示；0：隐藏，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function add(Request $request)
    {
        $param = $request->only('sub_cate_name', 'p_cate_ids', 'status');
        $v = app('validator')->make($param,[
            'sub_cate_name' => 'required|string|max:10',
            'p_cate_ids' => 'required|string',
            'status' => 'required|integer|in:1,0',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        app('repo_mall_product_sub_cate')->addOrEditProductSubCate($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /mall/product-sub-cate 编辑商品子分类
     *
     * @apiGroup 个性商城-商品子分类
     *
     * @apiParam {Int} id 子分类id，必须
     * @apiParam {String} sub_cate_name 子分类名称，必须
     * @apiParam {String} p_cate_ids 父分类，多个之间用英文逗号隔开，必须
     * @apiParam {Int} status 状态：1：显示；0：隐藏，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function edit(Request $request)
    {
        $param = $request->only('id', 'sub_cate_name', 'p_cate_ids', 'status');
        $v = app('validator')->make($param,[
            'id' => 'required|integer',
            'sub_cate_name' => 'required|string|max:10',
            'p_cate_ids' => 'required|string',
            'status' => 'required|integer|in:1,0',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        app('repo_mall_product_sub_cate')->addOrEditProductSubCate($param);
        return Response::sendData([]);
    }

    /**
     * @api {delete} /mall/product-sub-cate 删除商品子分类
     *
     * @apiGroup 个性商城-商品子分类
     *
     * @apiParam {Int} id 子分类id，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function del(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param,[
            'id' => 'required|integer',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $subCateId = $param['id'];

        $products = app('model_mall_products')->select('id')->where('sub_cate_id', $subCateId)->first();
        if ($products) throw new BasicException(0, '子分类下面还有商品，无法删除');

        DB::beginTransaction();
        try {
            //删除子分类
            app('model_mall_sub_category')->where('id', $subCateId)->delete();
            //删除子分类与父分类的关联
            app('model_mall_category_join')->where('sub_category_id', $subCateId)->delete();

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {get} /mall/product-sub-cate 商品子分类列表
     *
     * @apiGroup 个性商城-商品子分类
     *
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，1-100，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1, 序号
    "name": "气泡币专区", 子分类名称
    "status": 1, 状态：1：显示；0：隐藏
    "created_at": "2021-10-27 10:25:50", 添加时间
    "parent_categories": "坐骑,入场特效" 父分类
    }
    ],
    "first_page_url": "http://qipaoadmin/mall/product-sub-cate?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://qipaoadmin/mall/product-sub-cate?page=1",
    "next_page_url": null,
    "path": "http://qipaoadmin/mall/product-sub-cate",
    "per_page": 10,
    "prev_page_url": null,
    "to": 2,
    "total": 2
    },
    "message": ""
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('page', 'page_size');
        $v = app('validator')->make($param,[
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $pageSize = $param['page_size'] ?? 10;

        $list = app('model_mall_sub_category')
            ->select('id', 'name', 'status', 'created_at')
            ->paginate($pageSize)
            ->toArray();
        foreach ($list['data'] as &$v) {
            $categories = app('model_mall_categories')->from('ln_mall_categories as mc')
                ->leftJoin('ln_mall_category_join as mcj', 'mc.id', '=', 'mcj.category_id')
                ->select('mc.id', 'mc.title')
                ->where('mcj.sub_category_id', $v['id'])
                ->get()->toArray();
            $v['parent_categories_id'] = array_column($categories, 'id');
            $v['parent_categories_name'] = array_column($categories, 'title');
        }
        return Response::sendData($list);
    }

    /**
     * @api {get} /mall/product-sub-cate/all 获取所有商品子分类
     *
     * @apiGroup 个性商城-商品子分类
     *
     * @apiParam {Int} cate_id 父分类id
     * @apiParam {Int} status 状态，-1：不限制；0：隐藏；1（默认）：显示
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 1, 子分类id
    "name": "气泡币专区", 子分类名称
    }
    ],
    "message": ""
    }
     */
    public function all(Request $request)
    {
        $param = $request->only('cate_id', 'status');
        $v = app('validator')->make($param,[
            'cate_id' => 'integer',
            'status' => 'integer|in:-1,0,1',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $cateId = $param['cate_id'] ?? 0;
        $status = $param['status'] ?? -1;

        if ($cateId > 0) {
            $where[] = ['mcj.category_id', '=', $cateId];
        }
        if ($status != -1) {
            $where[] = ['msc.status', '=', $status];
        }

        $list = app('model_mall_sub_category')->from('ln_mall_sub_category as msc')
            ->leftJoin('ln_mall_category_join as mcj', 'msc.id', '=', 'mcj.sub_category_id')
            ->select('msc.id', 'msc.name')
            ->where($where)
            ->get();
        return Response::sendData($list);
    }
}